<template>
	<view class="y-flex y-flex-1 position-relative" style="background-color: rgba(0,0,0,.2);">
		<module-list
		ref="list"
		:component="components"
		:cell="cell"
		:comment="comments"
		:bounce="pageStyle.enableBounce"
		:back-top-show="pageStyle.enableBackTop"
		:refreshImage="pageStyle.pulldownRefreshImage"
		:pulldownable="pageStyle.enablePulldown == 1"
		:loadmoreable="pageStyle.enableLoadmore == 1"
		:loadingColor="pageStyle.loadingColor"
		:backTopImage="pageStyle.backTopImage"
		:params="detail"
		@scroll="handleScroll"
		@pulldown="handlePulldown"
		@loaded="handleModuleLoaded">
			<template #top v-if="detail && detail.uniqueId">
				<cell v-if="detail && detail.title">
					<find-detail ref="detail"
					:data="detail"
					:options="detailOptions"
					:bg-color="componentStyle['background-color']"
					:style="componentStyle"
					@utils="handleUtils"
					@startClick="handleStartClick"
					@continueClick="handleContinueClick"></find-detail>
				</cell>
				<cell v-if="items && items.length > 0">
					<find-items :data="items" :options="itemOptions" :style="componentStyle" @moreClick="handleMoreClick" @itemClick="handleItemClick"></find-items>
				</cell>
			</template>
		</module-list>
		<com-popup :visible.sync="contextShow" direction="center">
			<view class="y-flex position-relative" :style="{'width': windowWidth + 'px', 'height': windowHeight + 'px'}">
				<find-picture-preview class="y-flex-1" ref="pp" @change="handleChange"></find-picture-preview>
				<com-icon
				class="position-absolute right-30 top-70" name="round_close_fill"
				color="#999"
				size="65"
				@click="hideContext"></com-icon>
			</view>
		</com-popup>
	</view>
</template>

<script>
	import { setWallpaper, shareFile } from '@/assets/js/native.js'
	import { openDB, closeDB, insert, update } from '@/assets/database'
	import { pixelunit, hexToRgba } from '@/assets/js/util.js'
	import ModuleList from './components/ModuleList.vue' 
	import FindDetail from './components/FindModule/FindDetail.vue'
	import FindItems from './components/FindModule/FindItems.vue'
	import FindPicturePreview from './components/PicturePreview.vue'
	export default {
		inject: ['getPage', 'getComponentStyle', 'getPageStyle', 'getSkinColor', 'getWindowWidth', 'getWindowHeight', 'getQuery', 'navigate', 'confirm', 'toast', 'actionSheet', 'showItems'],
		components: {ModuleList, FindDetail, FindItems, FindPicturePreview},
		computed: {
			history () {
				return this.$store.getters['setting/GET_HISTORY']
			},
			skinColor () {
				return this.getSkinColor()
			},
			componentStyle () {
				const style = this.getComponentStyle()
				return {
					'margin-top': pixelunit(style.marginTop),
					'margin-bottom': pixelunit(style.marginBottom),
					'margin-left': pixelunit(style.marginLeft),
					'margin-right': pixelunit(style.marginRight),
					'background-color': hexToRgba(style.backgroundColor, style.backgroundOpacity),
					'border-radius': pixelunit(style.borderRadius)
				}
			},
			detailOptions () {
				return {
					startText: '欣赏图片',
					continueText: '继续欣赏',
					recordText: '查看记录'
				}
			},
			itemOptions () {
				return {
					title: '图片列表',
					unit: "张"
				}
			},
			network () {
				return this.$store.getters['network/GET']
			},
			//获取路由参数
			query () {
				return this.getQuery()
			},
			page () {
				return this.getPage()
			},
			pageStyle () {
				return this.getPageStyle()
			},
			//页面左右边距
			pageMarginGap () {
				return pixelunit(this.pageStyle?.pageMarginGap)
			},
			cell () {
				return this.page?.cell || {}
			},
			comments () {
				return this.page?.comments || {}
			},
			components () {
				return this.page?.components || []
			},
			//主题色
			themeColor () {
				return this.pageStyle.themeColor || this.skinColor.color_blue
			},
			content () {
				return this.detail.content ? `<div style="color: ${this.skinColor.color_1}">` + this.detail.content + '</div>' : ''
			},
			windowWidth () {
				return this.getWindowWidth()
			},
			windowHeight () {
				return this.getWindowHeight()
			},
			pixelunit () {
				return pixelunit
			}
		},
		data () {
			return {
				detail: {},//详情信息
				items: [],//图片集合
				current: -1,
				contextShow: false//展示图片查看页
			}
		},
		mounted () {
			this.$nextTick(this.handlePulldown)
		},
		beforeDestroy() {
			this.$refs.pp.destroy()
		},
		methods: {
			onShow () {
				this.$refs.detail && this.$refs.detail.getRecord()
			},
			onHide () {
				this.$refs.pp.pause()
			},
			onBackPress () {
				if ( this.contextShow ) {
					this.hideContext()
					return true
				}
				if ( this.detail.uniqueId && this.current >= 0 ) {
					if ( this.history == 0 ) {
						this.confirm({
							title: '记录提示',
							content: '当前看到' + (this.current + 1) + '/' + this.items.length + '位置\n\n是否记录',
							cancelText: '取消记录',
							confirmText: '保存记录',
							success: res => {
								if ( res.confirm ) {
									this.saveRecord()
								} else {
									uni.navigateBack()
								}
							}
						})
					} else if ( this.history == 1 ) this.saveRecord()
					else uni.navigateBack()
					return true
				}
				return false
			},
			async saveRecord () {
				try{
					await openDB()
					const record = this.$refs.detail.record
					if ( record.id ) {
						await update('record', {
							url: this.detail.url,
							title: this.detail.title || '',
							cover: this.detail.cover || '',
							current: this.current,
							current_title: (this.current + 1) + '/' + this.items.length,
							is_adult: this.detail.isAdult,
							source_id: this.detail.sourceId
						}, 'id = ' + record.id)
					} else {
						await insert('record', {
							unique_id: this.detail.uniqueId,
							url: this.detail.url,
							title: this.detail.title || '',
							cover: this.detail.cover || '',
							current: this.current,
							current_title: (this.current + 1) + '/' + this.items.length,
							is_adult: this.detail.isAdult,
							source_id: this.detail.sourceId
						})
					}
					closeDB()
					uni.navigateBack()
				}catch(e){
					closeDB()
					this.toast(e.message)
					setTimeout(() => {
						uni.navigateBack()
					}, 500)
				}
			},
			handleUtils (e) {
				this.$emit('utils', e)
			},
			handleStartClick () {
				this.goContext(0)
			},
			handleContinueClick (record) {
				this.goContext(record.current || 0)
			},
			handleMoreClick () {
				this.showItems({
					title: '图片列表',
					data: this.items,
					current: this.current,
					defaultTitle: this.detail.title,
					unit: '张图',
					success: res => {
						if ( res.confirm ) {
							this.goContext(res.current)
						}
					}
				})
			},
			handleItemClick (e) {
				this.goContext(e.index)
			},
			handleScroll (e) {
				this.$emit('scroll', Math.abs(e.contentOffset.y))
			},
			async handleChange ({current}) {
				this.current = parseInt(current)
				let item = this.items[current]
				if ( !item.src && !item.loading ) {
					this.$refs.pp.pause()
					this.$set(this.items[current], 'loading', true)
					const newImg = await this.handleGetContext(item)
					this.$set(this.items[current], 'loading', false)
					this.$set(this.items, current, newImg)
					this.$refs.pp.update(e.current, this.items[current])
					this.$refs.pp.play()
				}
			},
			async handlePulldown (callback) {
				try{
					this.detail = await this.handleGetDetail()
					this.items = await this.handleGetItems()
					this.$nextTick(function () {
						this.$refs.list && this.$refs.list.initModule(callback)
						this.$refs.detail && this.$refs.detail.getRecord()
					})
				}catch(e){
					this.$emit('loaded', true)
				}
			},
			handleModuleLoaded () {
				this.$emit('loaded', true)
				this.$refs.list && this.$refs.list.pulldownSuccess()
			},
			async handleGetDetail () {
				const detail = this.page?.detail || {}
				const staticData = await this.network.staticDataHandle(detail.staticData || {}, this.query)
				const dynamicData = detail.dynamicData
				const request = detail.request
				let data = {}
				if ( dynamicData && request ) {
					const newRequest = await this.network.requestHandle(request, this.query)
					const response = await this.network.$request(newRequest)
					data = await this.network.$list(dynamicData, response.data, response.taskId)
					data.uniqueId = data.id || this.network.getUniqueId(newRequest)
					if ( !data.shareUrl && !staticData.shareUrl ) data.shareUrl = await this.network.getShareUrl(newRequest)
				}
				return Object.assign({}, staticData, data)
			},
			async handleGetItems () {
				const items = this.page?.items || {}
				const params = Object.assign({}, this.query, this.detail)
				const staticData = items.staticData ? await this.network.staticDataHandle(items.staticData, params) : []
				const dynamicData = items.dynamicData
				const request = items.request
				let data = []
				if ( dynamicData && request ) {
					const newRequest = await this.network.requestHandle(request, params)
					const response = await this.network.$request(newRequest)
					data = await this.network.$list(dynamicData, response.data, response.taskId)
				}
				return staticData.concat(data).map(s => Object.assign({}, s, { loading: false }))
			},
			async handleGetContext (item) {
				const context = this.page?.context || {}
				const request = context.request
				const params = Object.assign({}, this.query, this.detail, item)
				const staticData = context.staticData ? await this.network.staticDataHandle(context.staticData, params) : {}
				const dynamicData = context.dynamicData || {}
				const newRequest = request ? await this.network.requestHandle(request, params) : null
				const response = newRequest ? await this.network.$request(newRequest) : {}
				const data = response ? await this.network.$list(dynamicData, response.data, response.taskId) : {}
				return Object.assign({}, item, staticData, data)
			},
			goContext (current) {
				if ( this.items.length == 0 ) {
					uni.showToast({
						title: '没有发现图片列表',
						icon: 'none'
					})
					return
				}
				this.current = current
				this.contextShow = true
				const items = this.items.map(item => Object.assign({}, this.detail, item))
				this.$refs.pp.init(items)
				this.$nextTick(() => {
					this.$refs.pp.slideTo(current)
				})
			},
			hideContext () {
				this.contextShow = false
				this.$refs.pp.pause()
				this.$refs.pp.destroy()
			}
		}
	}
</script>

<style>
</style>